package com.fengxu.gamescript.ui.cloud

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.fengxu.gamescript.R
import com.fengxu.gamescript.data.Conf
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.sdk27.coroutines.onClick
import java.util.*

/**
 * 搜索历史列表适配器
 */
class ScriptSearchHistoryListAdapter: BaseAdapter {

    private lateinit var mContext: Context

    // 搜索历史数据
    private lateinit var datas: Array<String>

    /**
     * 点击历史搜索记录事件
     */
    var clickItemEvent: ((String)->Unit)? = null

    constructor(ctx: Context){
        mContext = ctx
        datas = Conf.getConf().scriptSearchHistory.toTypedArray()
    }

    override fun getCount(): Int {
        return datas.size
    }

    override fun getItem(position: Int): Any {
        return datas[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    @SuppressLint("ViewHolder")
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view = LayoutInflater.from(mContext)
            .inflate(R.layout.list_search_history_item, parent, false)
        view.apply {
            val tv = findViewById<TextView>(R.id.list_search_history_note)
            tv.text = datas[position]
            // 绑定触发点击历史记录事件
            tv.onClick { clickItemEvent?.invoke(tv.text.toString()) }
            // 删除一条查询记录
            findViewById<View>(R.id.list_search_history_delete).onClick {
                if(datas.contains(tv.text)){
                    Conf.getConf().removeSearchHistory(tv.text.toString())
                }
            }
        }
        return view
    }

    override fun notifyDataSetChanged() {
        datas = Conf.getConf().scriptSearchHistory.toTypedArray()
        doAsync { Conf.saveConf(mContext) }
        super.notifyDataSetChanged()
    }

}